// 语言切换器模块
class LanguageSwitcher {
  constructor() {
    this.currentLanguage = 'zh-CN';
    this.i18nData = {};
    this.callbacks = [];
  }

  // 注册语言变化回调
  onLanguageChange(callback) {
    this.callbacks.push(callback);
  }

  // 通知语言变化
  notifyLanguageChange() {
    this.callbacks.forEach(callback => callback(this.currentLanguage));
  }

  // 切换语言
  async switchLanguage(lang) {
    if (lang === this.currentLanguage) {
      return true;
    }
    
    try {
      const response = await fetch(`./i18n/${lang}.json`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      this.i18nData = await response.json();
      this.currentLanguage = lang;
      
      // 保存语言设置到localStorage
      localStorage.setItem('whistle-language', lang);
      
      // 通知所有注册的回调
      this.notifyLanguageChange();
      
      return true;
    } catch (error) {
      console.error(`Failed to switch language to ${lang}:`, error);
      
      // 如果切换失败且不是英文，尝试回退到英文
      if (lang !== 'en-US') {
        console.log('Falling back to English...');
        return await this.switchLanguage('en-US');
      }
      
      return false;
    }
  }

  // 获取当前语言
  getCurrentLanguage() {
    return this.currentLanguage;
  }

  // 获取翻译文本
  getText(key) {
    const keys = key.split('.');
    let value = this.i18nData;
    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return key; // 如果找不到翻译，返回key
      }
    }
    return value || key;
  }

  // 检测系统语言
  detectSystemLanguage() {
    const savedLang = localStorage.getItem('whistle-language');
    if (savedLang) {
      return savedLang;
    }
    
    const systemLang = navigator.language || navigator.userLanguage;
    if (systemLang.startsWith('zh')) {
      return 'zh-CN';
    }
    return 'en-US';
  }

  // 初始化语言
  async init() {
    const lang = this.detectSystemLanguage();
    await this.switchLanguage(lang);
  }
}

// 创建全局实例
window.languageSwitcher = new LanguageSwitcher();

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
  module.exports = LanguageSwitcher;
}
